'use strict';

const Controller = require('egg').Controller;
const jwt = require("jsonwebtoken")
const giteePage = {
    grant_type: "authorization_code",
    client_id: "c1165cdedca5629fbca78ca98809dc220fdf94d75e3fabe14c5bdadded8d443b",
    redirect_uri: "http://localhost:3000/login",
    client_secret: "829f7fb81fc78902cf7b7cb3090939ad2ff2aaa53ec1d34cfb75a086698f450f",
};
class HomeController extends Controller {


    //第三方登录
    async giteeLogin() {
        const { ctx, app } = this;
        //解构从前端拿到的code
        const { code } = ctx.request.body;
        // 获取自己在第三方登录页面的token
        const resToken = await ctx.curl("https://gitee.com/oauth/token", {
            //请求方式是post    
            method: "post",
            data: {
                grant_type: giteePage.grant_type,
                code,
                client_id: giteePage.client_id,
                redirect_uri: giteePage.redirect_uri,
                client_secret: giteePage.client_secret,
            },
            //格式是json
            dataType: "json",
        });

        //获取自己在第三方登录页面的用户信息
        const userInfo = await ctx.curl(
            `https://gitee.com/api/v5/user?access_token=${resToken.data.access_token}`, { dataType: "json" }
        );
        //去数据库里面查看是否存在用户信息的id
        const data = await app.mysql.get("user", { id: userInfo.data.id });
        // console.log("data", data)
        //判断取反后的data有没有id,如果没有就说明php里面没有这个账户,如果有就说明php里面已经创建过账户了
        if (!data) {
            await app.mysql.insert("user", {
                id: userInfo.data.id,
                username: userInfo.data.login,
                password: "123",

            });
            ctx.body = {
                code: 1,
                token: jwt.sign(userInfo.data.id, "1907"),
            };
        } else {
            ctx.body = {
                code: 1,
                token: jwt.sign(userInfo.data.id, "1907"),
            };
        }
    }





    //登录
    async login() {
        const { app, ctx } = this;

        const { username, password } = ctx.request.body;
        const data = await app.mysql.get("user", { username, password });


        if (data) {
            ctx.body = {
                code: 1,
                token: jwt.sign(data.id, "1907"),
                msg: "登陆成功"
            };
        } else {
            //更改状态码

            // ctx.status = 401;
            ctx.body = {
                code: 0,
                msg: "用户名或者密码错误",
            };
        }
    }




    async getUserInfo() {
        const { ctx, app } = this
        //解构从前端传过来的authorization
        const { authorization } = ctx.request.headers

        //解密
        const id = jwt.verify(authorization, "1907")

        const userInfo = await app.mysql.get('user', { id })

        ctx.body = {
            code: 1,
            mesg: '全部数据',
            userInfo
        }
    }






}

module.exports = HomeController;